package com.youan.log.modules.audit.dataimport;

import com.youan.log.common.bean.ValidateResult;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.cache.ParamCache;
import org.springblade.core.tool.utils.SpringUtil;

import javax.sql.DataSource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 导入前检查
 * @author xsh
 * @date 2021/3/4 11:24
 * @param: null
 * @return
 */
public class PreImportValidate {

    public ValidateResult validate(String date) {
        ValidateResult validateResult = validateImportFolder();
        if(!validateResult.isPass()) {
            return validateResult;
        }

        validateResult = validateDBTable(date);
        if(!validateResult.isPass()) {
            return validateResult;
        }

        return validateResult;
    }

    private ValidateResult validateFileExist(String fileName) {
        String paramValue = ParamCache.getValue("data_import_path");
        Path path = Paths.get(paramValue, fileName);
        if(!Files.exists(path)) {
            return ValidateResult.failure(path.toString()+"文件不存在，无法导入数据!!");
        }
        return ValidateResult.success();
    }

    public ValidateResult validateImportFolder() {
        // 检查参数是否存在
        ValidateResult result = validateParamExist();
        if(!result.isPass()) {
            return result;
        }
        // 检查路径是否存在
        result = validateFileFolderExist();
        if(!result.isPass()) {
            return result;
        }
        return result;
    }

    public ValidateResult validateDateFolderName(String folderName) {
        String pattern = "((19|20)[0-9]{2})-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])";
        if(!Pattern.matches(pattern, folderName)) {
            return ValidateResult.failure("文件夹["+folderName+"]名称不符合格式要求,要求文件格式必须如[2020-12-13]所示!!");
        }
        return ValidateResult.success();
    }

    public ValidateResult validateDataFileName(Path dataFolderPath) {
        try {
            List<Path> paths = new ArrayList<>();
            try (Stream<Path> pathStream = Files.list(dataFolderPath)){
                paths = pathStream.collect(Collectors.toList());
            }

            if(CollectionUtils.size(paths) != 2) {
                return ValidateResult.failure(dataFolderPath.toString()+"下文件数必须为2");
            }

            String folderName = dataFolderPath.getFileName().toString();

            String fileName = paths.get(0).getFileName().toString();
            if(!StringUtils.equalsAny(fileName, folderName+"_sd_s_region.txt", folderName+"_sd_d_region.txt")) {
                return ValidateResult.failure(dataFolderPath.toString()+"下文件名有误!!");
            }

            fileName = paths.get(0).getFileName().toString();
            if(!StringUtils.equalsAny(fileName, folderName+"_sd_s_region.txt", folderName+"_sd_d_region.txt")) {
                return ValidateResult.failure(dataFolderPath.toString()+"下文件名有误!!");
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
            return ValidateResult.failure("读取文件夹下数据失败!!");
        }
        return ValidateResult.success();
    }

    public ValidateResult validateDBTable(String date) {
        String tableName = "region_data_" + date.replaceAll("-", "_");
        List<String> allTableNames = getAllTableNames();
        boolean tableExists = allTableNames.stream().filter(item -> StringUtils.equalsIgnoreCase(tableName, item)).findAny().isPresent();
        if(tableExists) {
            return ValidateResult.failure("表"+tableName+"已经存在,无法导入该天数据!!");
        }
        return ValidateResult.success();
    }

    private List<String> getAllTableNames() {
        List<String> result = new ArrayList<>();
        Connection connection = null;
        ResultSet resultSet = null;
        try {
            DataSource dataSource = SpringUtil.getBean(DataSource.class);
            connection = dataSource.getConnection();
            DatabaseMetaData metaData = connection.getMetaData();
            resultSet = metaData.getTables(null, null, null, null);
            while (resultSet.next()) {
                String tableName = resultSet.getString("TABLE_NAME");
                result.add(tableName);
            }
        } catch (SQLException exception) {
            exception.printStackTrace();
        } finally {
            if (null!=connection) {
                try{
                    connection.close();
                }catch (Exception e1) {
                }
            }
            if (null!=resultSet) {
                try {
                    resultSet.close();
                }catch (Exception e2) {
                }
            }
        }
        return result;
    }

    private ValidateResult validateFileFolderExist() {
        String paramValue = ParamCache.getValue("data_import_path");
        Path path = Paths.get(paramValue);
        if(!Files.exists(path)) {
            return ValidateResult.failure("请检查文件夹路径["+paramValue+"]是否存在!!");
        }

        if(!Files.isDirectory(path)) {
            return ValidateResult.failure("路径["+paramValue+"]对应的文件不是文件夹!!");
        }

        return ValidateResult.success();
    }

    private ValidateResult validateParamExist() {
        String paramValue = ParamCache.getValue("data_import_path");
        if(StringUtils.isBlank(paramValue)) {
            return ValidateResult.failure("系统中未配置参数[data_import_path]!!");
        }
        return ValidateResult.success();
    }
}
